package com.gsy.springbootshiro.config;

import com.gsy.springbootshiro.pojo.User;
import com.gsy.springbootshiro.service.UserServiceImp;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @program: springboot-shiro
 * @description:
 * @author: GSY
 * @create: 2020-03-16 14:32
 **/
public class UserRealm extends AuthorizingRealm {


    @Autowired
    UserServiceImp userServiceImp;

    @Override//授权
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //info.addStringPermission("user:add");
        Subject subject = SecurityUtils.getSubject();
        User currentUser = (User) subject.getPrincipal();//这个用户信息从认证传过来
        info.addStringPermission(currentUser.getPerms());

        return info;
    }

    @Override//认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("执行了认证");

      /* String username = "root";
       String password = "123456";*/

        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

        //连接真实数据库
        User user = userServiceImp.queryByName(userToken.getUsername());

        if (user == null){//没有这个人
            return null;
        }

        Subject currentSubject = SecurityUtils.getSubject();
        Session session = currentSubject.getSession();
        session.setAttribute("loginUser",user);

      /*  if (!userToken.getUsername().equals(username)){
            return null;//抛出用户名错误异常
        }*/

        //密码认证
        return new SimpleAuthenticationInfo(user,user.getPud(),"");
    }
}
